(function(){
  var TextCounter = function(elem) {
    this.elem = elem;
  };
  TextCounter.prototype = {};

  /**
   * Event handler for when typing occurs in a field.
   */
  TextCounter.prototype.handleTyping = function(evt) {
    evt = evt ? evt : window.event;
    var elem;

    if (evt.target)
      elem = evt.target;
    else if (evt.srcElement)
      elem = evt.srcElement;
    if (elem) {
      // Safari bug:
      if (elem.nodeType == 3)
        elem = elem.parentNode;

      if (elem.TextCounter) {
        elem.TextCounter.updateCount();
      }
    }
  };

  /**
   * Event handler for when mouse hovers over the count bar.
   */
  TextCounter.prototype.handleCountBarHover = function(evt) {

  };

  /**
   * Initialize this text counter.
   *
   * Create the DOM element for the display if needed, and install the
   * event handlers.
   */
  TextCounter.prototype.initialize = function() {
    if (!this.countDisplay) {
      this.countDisplay = document.createElement("div");
      this.countDisplay.style.width = this.elem.style.width;
      this.updateCount();
      this.elem.parentNode.insertBefore(this.countDisplay, this.elem);
    }
    this.elem.addEventListener("keyup", this.handleTyping, false);
  };

  /**
   * Update the count in the display.
   */
  TextCounter.prototype.updateCount = function(cnt) {
    if (this.countDisplay) {
      var count = this.elem.value.length;
      this.countDisplay.innerHTML = "characters: " + count;
    }
  };

  // Add a TextCounter to every textarea on the page.
  var elems = document.getElementsByTagName("textarea");
  for (var i = 0; i < elems.length; i++) {
    var elem = elems[i];
    elem.TextCounter = new TextCounter(elem);
    elem.TextCounter.initialize();
  }
})();
